<?php
namespace app\index\controller;

use app\index\service\PackageService;
use think\Controller;
use think\Db;
use think\Env;

class Index extends Controller
{
    public function index()
    {
        $ids = $_GET['f'];
        $data = json_decode(base64_decode(urldecode($ids)),true);
        $refer = strtolower($_SERVER['HTTP_USER_AGENT']);
        $packageInfo = Db::name('package')
            ->where(['relation_package_id'=>$data['relation_package_id']])
            ->field('id,sdk_version')->select();
        $arr = [];
        foreach ($packageInfo as $k=>$v){
            $arr[$v['sdk_version']] = $v['id'];
        }
        if (strpos($refer, 'iphone') !== false || strpos($refer, 'ios') !== false || strpos($refer, 'macintosh') !== false || strpos($refer, 'ipad') !== false){
            if(!isset($arr[2])){
                $this->error('ios分包不存在');
            }
            $applyInfo = $this->getPackageInfo($arr[2],$data['promote_id']);
        } else if (strpos($refer, 'android') !== false || strpos($refer, 'silk/') !== false || strpos($refer, 'kindle') !== false || strpos($refer, 'blackberry') !== false || strpos($refer, 'opera mini') !== false || strpos($refer, 'opera mobi') !== false){
            if(!isset($arr[1])){
                $this->error('安卓分包不存在');
            }
            $applyInfo = $this->getPackageInfo($arr[1],$data['promote_id']);
        }else{
            if(!isset($arr[1])){
                $this->error('安卓分包不存在');
            }
            $applyInfo = $this->getPackageInfo($arr[1],$data['promote_id']);
//            if(!isset($arr[4])){
//                $this->error('PC分包不存在');
//            }
//            $applyInfo = $this->getPackageInfo($arr[4],$data['promote_id']);
        }
        if(!$applyInfo){
            $this->error('分包打包中！');
        }
        $packageInfo = Db::name('package')->where('id',$applyInfo['package_id'])->find();
        $this->assign('packageInfo',$packageInfo);

        if(strpos($refer, 'micromessenger') !== false || strpos($refer, 'windows phone') !== false){
            $this->assign('sdk_version',$applyInfo['sdk_version']);
            return $this->fetch('down_file_weixin');
        }
        if (strpos($refer, 'micromessenger') !== false && (strpos($refer, 'iphone') !== false || strpos($refer, 'ipad') !== false)) {
            return $this->fetch('down_file_weixin');
        }
        if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false ) {
            return $this->fetch('down_file_weixin');
        }


        $downUrl = $applyInfo['pack_url'];
        if($applyInfo['sdk_version'] == 2){
            $iosPackageInfo = Db::name('package')
                ->where(['id'=>$arr[2]])
                ->field('id,appstore_url,relation_package_name')->find();
            if(!empty($iosPackageInfo['appstore_url'])){
                $this->assign('data',$iosPackageInfo);
                $os_version = get_os_version();
                $ip = get_client_ip();
                $qsApiUrl = Env('requestUrl.qsApiUrl')."index/index/adid/{$data['promote_id']}?os_version={$os_version}&ip={$ip}&os_type=1&source=1";
//                write_log('INFO', 'Index.php', '上报地址:'.$qsApiUrl, 'appstore', true);
//                curl_get($qsApiUrl);
                $this->assign('qsApiUrl',base64_encode($qsApiUrl));
                return $this->fetch('appstore');
            }
            $downUrl = "itms-services://?action=download-manifest&url={$applyInfo['plist_url']}";
        }
        $this->assign('downUrl',$downUrl);
        $package_landing_template_id = Db::name('package_config')->where('package_id',$applyInfo['package_id'])->value('package_landing_template_id');
        if($applyInfo['package_landing_template_id']){
            $package_landing_template_id = $applyInfo['package_landing_template_id'];
        }
        if($package_landing_template_id){
            $template = Db::name('package_landing_template')->where('id',$package_landing_template_id)->find();
            $path =  "uploads".$template['path'];
        }else{
            $path = "uploads/template/qnssfsqn";
        }
        $this->assign('path',"/".$path);
        return $this->fetch($path.'/index.html');
    }

    public function getPackageInfo($package_id,$promote_id){
        $row = Db::name('apply')
            ->where(['package_id'=>$package_id,'promote_id'=>$promote_id])
            ->field('id,package_id,sdk_version,enable_status,pack_url,plist_url,package_landing_template_id,status')
            ->find();
        return $row;
    }
    public function pcGame()
    {
        $ids = $_GET['f'];
        $data = json_decode(base64_decode(urldecode($ids)),true);
        $applyInfo = $this->getPackageInfo($data['package_id'],$data['promote_id']);
        if(!$applyInfo){
            $this->error('分包打包中！');
        }
        $downUrl = $applyInfo['pack_url'];
        header("Location:".$downUrl);
    }
    // 下载分包
    public function downGame()
    {
        $promote_id = $_GET['promote_id'];
        $package_id = $_GET['package_id'];
        $applyInfo = $this->getPackageInfo($package_id,$promote_id);
        if(!$applyInfo){
            $this->error('分包打包中！');
        }
        $downUrl = $applyInfo['pack_url'];
        if($applyInfo['sdk_version'] == 2){
            $downUrl = "itms-services://?action=download-manifest&url={$applyInfo['plist_url']}";;
        }
        header("Location:".$downUrl);
    }
    /**
     * 直接下载分包，自动识别 安卓 iOS=》有商店包优先下载商店包
     * $package_id  int 关联游戏包id
     * $promote_id  int 推广员id
     */
    public function downGameNew(){
        $promote_id = $_GET['promote_id'];
        $relation_package_id = $_GET['package_id'];
        $refer = strtolower($_SERVER['HTTP_USER_AGENT']);
        if (strpos($refer, 'iphone') !== false || strpos($refer, 'ios') !== false || strpos($refer, 'macintosh') !== false || strpos($refer, 'ipad') !== false){
            $sdk_version = 2;
        } else{
            $sdk_version = 1;
        }
        if($sdk_version == 1){
            $map['sdk_version'] = 1;
            $map['relation_package_id'] = $relation_package_id;
            $packageInfo = Db::name('package')->where($map)->find();
            if(!$packageInfo){
                $package_id = $this->getAnPackage($relation_package_id);
            }else{
                $package_id = $packageInfo['id'];
            }
            $applyInfo = $this->getPackageInfo($package_id,$promote_id);
        }else{
            $os_version = get_os_version();
            $ip = get_client_ip();
            $qsApiUrl = Env('requestUrl.qsApiUrl')."index/index/adid/{$promote_id}?os_version={$os_version}&ip={$ip}&os_type=1&source=1";
            $map['sdk_version'] = 2;
            $map['relation_package_id'] = $relation_package_id;
            $packageInfo = Db::name('package')->where($map)->find();
            if(!$packageInfo){
                $this->error('ios分包不存在');
            }else{
                //查询是否关联商店包，优先下载商店包
                if($packageInfo['appstore_url']){
                    write_log('INFO', 'Index.php', '上报地址:'.$qsApiUrl, 'appstore', true);
                    curl_get($qsApiUrl);
                    header("Location:".$packageInfo['appstore_url']);exit();
                }else{
                    $applyInfo = $this->getPackageInfo($packageInfo['id'],$promote_id);
                    if($packageInfo['game_appid']){
                        $newPackage = Db::name('package')
                            ->where('game_appid',$packageInfo['game_appid'])
                            ->where('id','<>',$packageInfo['id'])
                            ->find();
                        if($newPackage['appstore_url']){
                            write_log('INFO', 'Index.php', '上报地址:'.$qsApiUrl, 'appstore', true);
                            curl_get($qsApiUrl);
                            header("Location:".$newPackage['appstore_url']);exit();
                        }else{
                            if(!$applyInfo['plist_url']){
                                $applyInfo = $this->getPackageInfo($newPackage['id'],$promote_id);
                            }
                        }
                    }
                    if(!$applyInfo['plist_url']){
                        $this->error('分包打包中，请稍后重试！');
                    }
                }
            }
        }
        if(!$applyInfo){
            $this->error('分包打包中，请稍后重试！');
        }
        if($applyInfo['status'] == 1 && $applyInfo['enable_status'] == 1){
            $downUrl = $applyInfo['pack_url'];
            if($sdk_version == 2){
                $downUrl = "itms-services://?action=download-manifest&url={$applyInfo['plist_url']}";;
            }
            header("Location:".$downUrl);
        }else{
            $this->error('分包打包中，请稍后重试！');
        }

    }
    /**
     * 根据iOS获取安卓包id，不存在直接返回错误提示
     * $relation_package_id  int 关联游戏包id
     */
    public function getAnPackage($relation_package_id){
        $map['sdk_version'] = 2;
        $map['relation_package_id'] = $relation_package_id;
        $iosPackage = Db::name('package')->where($map)->find();
        // 获取关联的ios包
        $new_relation_package_id = Db::name('package')
            ->where('game_appid',$iosPackage['game_appid'])
            ->where('id','<>',$iosPackage['id'])
            ->value('relation_package_id');
        $anPackageId = Db::name('package')
            ->where(['relation_package_id'=>$new_relation_package_id,'sdk_version'=>1])
            ->value('id');
        if(!$anPackageId){
            $this->error('安卓分包不存在');
        }
        return $anPackageId;
    }
    /**
     * web落地页地址
     */
    public function webIndex()
    {
        $ids = $_GET['f'];
        $data = json_decode(base64_decode(urldecode($ids)),true);
        $res = (new PackageService())->getPackageDownInfo($data['package_id'],$data['promote_id']);
        $this->assign('path',"/".$res['path']);
        $this->assign('packageInfo',$res);
        $this->assign('anDownUrl',$res['anDownUrl']);
        $this->assign('pcDownUrl',$res['pcDownUrl']);
        $this->assign('iosDownUrl',$res['iosDownUrl']);
        return $this->fetch($res['path'].'/index.html');
    }
}
